package com.san.warnings.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.san.base.controller.BaseController;
import com.san.common.annotation.Log;
import com.san.common.utils.ExcelUtil;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.R;
import com.san.system.domain.UserDO;
import com.san.system.service.UserService;
import com.san.warnings.domain.WarningsBusiDO;
import com.san.warnings.domain.WarningsCompanyDO;
import com.san.warnings.domain.WarningsFollowDO;
import com.san.warnings.domain.WarningsModelDO;
import com.san.warnings.service.WarningsService;

/**
 * 信用预警
 * 
 * @author hulp
 * @date 2020年3月25日15:08:22
 *
 */
@Controller
@RequestMapping("warn/warnings")
public class WarningsController extends BaseController {

	private String PREFIX = "warnings";
	private static final Logger logger = LoggerFactory.getLogger(WarningsController.class);

	@Autowired
	WarningsService warningService;

	@Autowired
	UserService userService;

	@GetMapping("")
	// @RequiresPermissions("warn:warning:view")
	String view(Model model) {
		return PREFIX + "/view";
	}

	/**
	 * 查询信用预警列表
	 * 
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/list")
	// @RequiresPermissions("warn:warning:view")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			// 查询列表数据
			Query query = new Query(params);
			List<WarningsModelDO> list = warningService.list(query);
			int total = warningService.count(query);
			pageUtils = new PageUtils(list, total);
		} catch (Exception e) {
			logger.error("获取信用预警失败", e);
		}
		return pageUtils;
	}

	/**
	 * 添加预警页面
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("/add")
	// @RequiresPermissions("warn:warning:add")
	String add(Model model) {
		return PREFIX + "/add";
	}

	/**
	 * 添加预警页面
	 * 
	 * @param earlyWarningDO
	 * @return
	 */
	// @RequiresPermissions("warn:warning:add")
	@Log("添加预警页面")
	@PostMapping("/save")
	@ResponseBody
	R save(WarningsModelDO warningsModelDO) {
		warningsModelDO.setDelFlag(Long.valueOf(-2));
		try {
			if (warningService.save(warningsModelDO) > 0) {
				return R.ok();
			}
		} catch (Exception e) {
			logger.error("保存预警模板出错", e);
			return R.error();
		}
		return R.error();
	}

	/**
	 * 控制信用预警状态
	 * 
	 * @param id
	 * @param delFlag
	 * @return
	 */
	@PostMapping(value = "/changeStatus")
	// @RequiresPermissions("warn:warning:changeStatus")
	@ResponseBody
	public R changeStatus(Long id, Long delFlag) {
		String label = "";
		if (delFlag == 1) {
			label = "禁用";
		} else if (delFlag == 0) {
			label = "启用";
		} else if (delFlag == -1) {
			label = "删除";
		}
		WarningsModelDO warningsModelDO = new WarningsModelDO();
		warningsModelDO.setWarnId(id);
		warningsModelDO.setDelFlag(delFlag);
		try {
			warningService.changeStatus(warningsModelDO);
			return R.ok("信用预警" + label + "成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok("信用预警" + label + "失败");
	}

	/**
	 * 编辑信用预警模型
	 * 
	 * @param model
	 * @param tableId 表ID
	 * @return
	 */
	@Log("编辑信用预警模型信息")
	// @RequiresPermissions("warn:warning:edit")
	@GetMapping("/edit/{warnId}")
	String edit(Model model, @PathVariable("warnId") Long warnId) {
		WarningsModelDO warningsModelDO = null;
		try {
			warningsModelDO = warningService.getById(warnId);
		} catch (Exception e) {
			logger.error("获取信用预警信息出错", e);
		}
		model.addAttribute("warningsModelDO", warningsModelDO);
		return PREFIX + "/edit";
	}

	/**
	 * 批量添加模型指标
	 * 
	 * @param ModelId            模型ID
	 * @param WarningsBusiDOList 模型指标List
	 * @return
	 */
	// @RequiresPermissions("md:technical:add")
	@Log("批量添加模型指标")
	@PostMapping("/batchBusiAdd/{modelId}")
	@ResponseBody
	@Transactional
	R batchColumnsAdd(@PathVariable("modelId") Long modelId, @RequestBody List<WarningsBusiDO> WarningsBusiDOList) {
		int r = 0;
		try {
			WarningsModelDO warningsModelDO = warningService.getById(modelId);
			warningsModelDO.setDelFlag(Long.valueOf(1));
			warningService.changeStatus(warningsModelDO);

			warningService.batchBusiRemove(modelId);
			r = warningService.batchBusiAdd(WarningsBusiDOList);
		} catch (Exception e) {
			logger.error("批量添加模型指标失败", e);
			return R.error("批量添加模型指标失败");
		}
		if (r > 0) {
			return R.ok();
		}

		return R.error("批量添加模型指标失败");
	}

	/**
	 * 查询信用预警指标列表
	 * 
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listBusi")
	// @RequiresPermissions("warn:warning:view")
	public PageUtils listBusi(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		try {
			// 查询列表数据
			Query query = new Query(params);
			List<WarningsBusiDO> list = warningService.listBusi(query);
			int total = warningService.countBusi(query);
			pageUtils = new PageUtils(list, total);
		} catch (Exception e) {
			logger.error("获取信用预警失败", e);
		}
		return pageUtils;
	}

	/**
	 * 信用预警订阅页面
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("/myFollow")
	// @RequiresPermissions("warn:warning:follow")
	String myFollow(Model model) {
		return PREFIX + "/myFollow";
	}

	/**
	 * 查询我订阅的信用预警列表
	 * 
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listMyFollow")
	// @RequiresPermissions("warn:warning:follow")
	public PageUtils listMyFollow(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		UserDO userDO;
		try {
			userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			// 查询列表数据
			Query query = new Query(params);
			query.put("deptId2", deptId);
			List<WarningsModelDO> list = warningService.listFollow(query);
			int total = warningService.countFollow(query);
			pageUtils = new PageUtils(list, total);
		} catch (Exception e) {
			logger.error("获取我订阅的信用预警列表失败", e);
		}
		return pageUtils;
	}

	/**
	 * 信用预警订阅页面
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("/follow")
	// @RequiresPermissions("warn:warning:follow")
	String follow(Model model) {
		return PREFIX + "/follow";
	}

	/**
	 * 查询信用预警订阅列表
	 * 
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listFollow")
	// @RequiresPermissions("warn:warning:follow")
	public PageUtils listFollow(@RequestParam Map<String, Object> params) {
		PageUtils pageUtils = null;
		UserDO userDO;
		try {
			// 查询列表数据
			Query query = new Query(params);
			userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			query.put("deptId1", deptId);
			List<WarningsModelDO> list = warningService.listFollow(query);
			int total = warningService.countFollow(query);
			pageUtils = new PageUtils(list, total);
		} catch (Exception e) {
			logger.error("获取信用预警订阅列表失败", e);
		}
		return pageUtils;
	}

	/**
	 * 控制信用预警订阅状态
	 * 
	 * @param id
	 * @param delFlag
	 * @return
	 */
	@PostMapping(value = "/changeFollowStatus")
	// @RequiresPermissions("warn:warning:changeStatus")
	@ResponseBody
	public R changeFollowStatus(Long warnId, Long status) {
		String label = "";
		if (status == -1) {
			label = "退订";
		} else {
			label = "订阅";
		}
		Long deptId = null;
		try {
			UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
			deptId = userDO.getDeptId();
		} catch (Exception e) {
			logger.error("获取用户信息失败", e);
		}
		WarningsFollowDO warningsFollowDO = new WarningsFollowDO();
		warningsFollowDO.setWarnId(warnId);
		warningsFollowDO.setStatus(status);
		warningsFollowDO.setDeptId(deptId);
		try {
			if (status == -1) {
				// 退订预警
				warningService.followRemove(warningsFollowDO);
				// 删除该预警的对应企业名单
				warningService.batchRemoveData(warnId, deptId);
				return R.ok("信用预警" + label + "成功");
			} else if (status == 0) {
				warningService.followAdd(warningsFollowDO);
				return R.ok("信用预警" + label + "成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok("信用预警" + label + "失败");
	}
	
	@GetMapping("/followReview")
	//@RequiresPermissions("warn:warning:followReview")
	String followReview(Model model) {
		return PREFIX + "/followReview";
	}
	
	/**
	 * 查询信用预警审核列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listFollowReview")
	//@RequiresPermissions("warn:warning:followReview")
	public PageUtils listFollowReview(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		try{
			// 查询列表数据
			Query query = new Query(params);
			List<WarningsFollowDO> list = warningService.listFollowReview(query);
			int total = warningService.countFollowReview(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取信用预警审核失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 审核信用预警订阅状态
	 * @param id
	 * @param delFlag
	 * @return
	 */
	@PostMapping(value = "/reviewFollowStatus")
	//@RequiresPermissions("warn:warning:changeStatus")
	@ResponseBody
	public R reviewFollowStatus(Long followId,Long status ) {
		String label = "";
		if (status == 1) {
			label = "通过";
		} else {
			label = "拒绝";
		}
		WarningsFollowDO warningsFollowDO = new WarningsFollowDO();
		warningsFollowDO.setFollowId(followId);
		warningsFollowDO.setStatus(status);
		try {
				warningService.reviewFollowStatus(warningsFollowDO);
				return R.ok(label + "审核成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok(label + "审核失败");
	}
	
	/**
	 * 信用预警订阅页面
	 * @param model
	 * @return
	 */
	@GetMapping("/myFollowDetail/{warnId}")
	//@RequiresPermissions("warn:warning:follow")
	String myFollowDetail(Model model, @PathVariable("warnId") Long warnId) {
		Long total = null;
		try {
			UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			total = warningService.myFollowCount(warnId,deptId);
		} catch (Exception e) {
			logger.error("获取信用预警信息出错", e);
		}
		model.addAttribute("warnId", warnId);
		model.addAttribute("total", total);
		return PREFIX + "/myFollowDetail";
	}
	
	/**
	 * 信用预警订阅页面
	 * @param model
	 * @return
	 */
	@GetMapping("/dataImport/{warnId}")
	//@RequiresPermissions("warn:warning:follow")
	String dataImport(Model model, @PathVariable("warnId") Long warnId) {
		model.addAttribute("warnId", warnId);
		return PREFIX + "/dataImport";
	}
	
	/**
	 * 预警数据导入
	 * @param warnId
	 * @param file
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@PostMapping("/doCheck")
	//@RequiresPermissions("warn:warning:view")
	@Log("预警数据导入")
	public R doCheck(@RequestParam(value="warnId",required=false)Long warnId,@RequestParam(value="excelFile",required=false)MultipartFile file,HttpServletRequest request,HttpServletResponse response) {
		Map<String,Object> resultMap = null;
		try{
			MultipartFile excelFile = file;
			if(excelFile != null){
				String fileName = excelFile.getOriginalFilename();
				String type = fileName.substring(fileName.lastIndexOf(".")+1);
				if("xlsx".equals(type) || "xls".equals(type)){
					List<List<String>> datas = ("xlsx".equals(type) ? ExcelUtil.readXlsx(excelFile.getInputStream()) : ExcelUtil.readXls(excelFile.getInputStream()));
					//读取的内容后处理
					UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
					Long deptId = userDO.getDeptId();
					resultMap = warningService.batchAddData(warnId,deptId,datas);
				}else{
					return R.error("请导入Excel文件");
				}
			}
		} catch(Exception e) {
			logger.error("匹配核查模板失败",e);
		}
		return R.ok(resultMap);
	}
	
	/**
	 * 查询信用预警企业列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/listMyFollowDetail")
	//@RequiresPermissions("warn:warning:view")
	public PageUtils listMyFollowDetail(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		try{
			// 查询列表数据
			UserDO userDO = (UserDO) userService.getById(getUser().getUserId());
			Long deptId = userDO.getDeptId();
			Query query = new Query(params);
			query.put("deptId", deptId);
			query.put("status", null);
			List<WarningsCompanyDO> list = warningService.listMyFollowDetail(query);
			int total = warningService.CountMyFollowDetail(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取信用预警失败",e);
		}
		return pageUtils;
	}

}
